﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Collections.Generic;
using CMN.Common;
using CMN.Entity;
using CMN.Models;
using CMN.Models.Interfaces;
namespace CMN.Forms
{
    public class AsyncUpdateUrlLog : AsyncBase
    {

        public string StrWhere = string.Empty;
        public AsyncUpdateUrlLog(ISynchronizeInvoke target)
            : base(target)
        {
           
        }
        //根据任务ID执行任务
        protected override void AsyncWork()
        {
            Update();                    
                
        }

        //已知任务步骤,任务可以取消
        public  void Update()
        {
           
            IDataService<SendUrlLogEntity> urlSv = ServiceBuilder.BuildSendUrlLogService();
            QueryParam qp = new QueryParam();
            qp.Where = StrWhere;
            int recordNum=0;
            List<SendUrlLogEntity> urlList = urlSv.List(qp, out recordNum);

            this.m_action = urlList.Count;
            bool is_cancel = false;
            string strContent="";
            for (int i = 0; i < urlList.Count; ++i)
            {
                //调用基类的方法检查任务是否取消
                is_cancel = isCnacel();
                if (is_cancel)
                    break;
                
                try
                {
                    strContent = Utils.GetRequestString("http://www.baidu.com/s?wd=" + Utils.UrlEncode( urlList[i].SendUrl)+"&ie=utf-8&tn=baidu", 16000, 1, System.Text.Encoding.GetEncoding("utf-8"), null);
                    if (Utils.GetCutString(strContent, "百度为您找到相关结果约", "个", false) != "")
                    {
                        urlList[i].IsIndex = "是";
                        urlSv.Update(urlList[i]);
                    }
                    else
                    {
                        urlList[i].IsIndex = "否";
                        urlSv.Update(urlList[i]);
                    }
                }
                catch (Exception ex)
                {
                    AppLog.Write(ex.Message, AppLog.LogMessageType.Error);
                }
                OnTaskProgress(this, i);
                System.Threading.Thread.Sleep(100);
            }
            if (!is_cancel)
                OnTaskDone(this, null);
            this.Stop();
           
        }

    }
}
